{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2d123403-f5a7-4617-9465-6d1d4fb939cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import random\n",
    "import shutil\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a5cb638c-9a5d-47ea-bfc9-04e7063b905a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_test(img_path, label_path, test_img, test_label):\n",
    "    img_files = os.listdir(img_path)\n",
    "    num_imgs = len(img_files)\n",
    "    num_to_move = int(num_imgs * 0.3)  # 计算需要移动的图片数量\n",
    "    \n",
    "    os.makedirs(test_img, exist_ok=True)\n",
    "    os.makedirs(test_label, exist_ok=True)\n",
    "\n",
    "    # 随机选择30%的图片\n",
    "    selected_imgs = random.sample(img_files, num_to_move)\n",
    "    for img_file in selected_imgs:\n",
    "        # 移动图片文件\n",
    "        img_src = os.path.join(img_path, img_file)\n",
    "        img_dst = os.path.join(test_img, img_file)\n",
    "        shutil.move(img_src, img_dst)\n",
    "        \n",
    "        # 移动对应的标签文件\n",
    "        label_file = os.path.splitext(img_file)[0] + '.txt' \n",
    "        label_src = os.path.join(label_path, label_file)\n",
    "        label_dst = os.path.join(test_label, label_file)\n",
    "        if os.path.exists(label_src):  \n",
    "            shutil.move(label_src, label_dst)\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5d3606cb-6204-4a00-867b-61c4e671bbf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "label_path = '/root/autodl-tmp/training/label_2' #'/root/autodl-tmp/test_label'\n",
    "img_path = '/root/autodl-tmp/training/image_2' #'/root/autodl-tmp/test_img'\n",
    "test_img = '/root/autodl-tmp/testing/image_2'\n",
    "test_label = '/root/autodl-tmp/testing/label_2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0ca57209-8fdc-4d8b-b08d-5e099b7bdb20",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_test(img_path, label_path, test_img, test_label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c188692-7b0e-4d72-af90-05af878e3740",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
